package com.starblink.search.result.ui.fragment.user

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
import androidx.recyclerview.widget.LinearLayoutManager
import com.starblink.android.basic.adapter.MutableAdapter
import com.starblink.android.basic.base.fragment.BaseTVMLazyLoadingFragment
import com.starblink.basic.apollo.ext.ApolloValSetExt
import com.starblink.basic.apollo.ext.ApolloValSetExt.apolloValue
import com.starblink.android.basic.ext.string
import com.starblink.android.basic.extension.lazyOnNone
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.android.basic.util.bus.bean.FollowUserEvent
import com.starblink.android.basic.util.post.CommonMutateManage
import com.starblink.rocketreserver.fragment.AccountF
import com.starblink.search.R
import com.starblink.search.databinding.CellSearchUserBinding
import com.starblink.search.databinding.FgmSearchUserResultBinding
import com.starblink.search.result.ui.cell.UserResultCell

/**
 * 搜索结果-用户结果
 */
internal class UserResultFragment :
    BaseTVMLazyLoadingFragment<FgmSearchUserResultBinding, UserResultVM>() {

    override fun emptyMessage(): String = string(R.string.search_not_found)

    private val adapter by lazyOnNone {
        MutableAdapter(viewModel.contentList).apply {
            addVhDelegate {
                UserResultCell(CellSearchUserBinding.inflate(layoutInflater, it, false)) { model, position ->
                    refreshState(model, position)
                }
            }
        }
    }

    override fun initData() {
        viewModel.keyworkd = arguments?.getString(QUERY_WORD) ?: ""
    }

    override fun initView(view: View) {
        viewBinding.recycler.adapter = adapter
        viewBinding.recycler.layoutManager = LinearLayoutManager(requireContext())

        viewBinding.refresher.setOnLoadMoreListener {
            viewModel.pageNo++
            viewModel.fetchUsers()
        }
        FlowBus.with<FollowUserEvent>(FlowConst.FOLLOW_USER_EVENT).register(this) { event ->
            viewModel.contentList.indexOfFirst { it.id == event.id }.takeIf { it > -1 }
                ?.let { index ->
                    viewModel.contentList[index].apolloValue("relationCode", event.relationCode)
                    adapter.notifyItemChanged(index)
                }
        }
    }

    override fun initLoad() {

    }

    override fun startObserve() {

        viewModel.contentLiveData.observe(this) {
            adapter.refreshAll()
            if (it) {
                viewBinding.refresher.finishLoadMore()
            } else {
                viewBinding.refresher.finishLoadMoreWithNoMoreData()
            }
        }
    }

    override fun getViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): FgmSearchUserResultBinding = FgmSearchUserResultBinding.inflate(layoutInflater)

    override fun onLazyInitData() {
        viewModel.fetchUsers()
    }

    private fun refreshState(model: AccountF, position: Int) {
        CommonMutateManage.followUser(requireContext(), model.id, model.relationCode, refreshState = {}) {
            ApolloValSetExt.setApolloVal<AccountF>(model, "relationCode", it)
            adapter.notifyItemChanged(position)
        }
    }

    companion object {

        const val QUERY_WORD = "query_word"

        fun newInstance(queryWord: String) = UserResultFragment().apply {
            arguments = bundleOf(QUERY_WORD to queryWord)
        }

    }
}